package io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

public class NioClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress("localhost", 8080));
        while(!socketChannel.finishConnect()) {
            Thread.sleep(100);
        }
        System.out.println("连接到服务器");

        System.out.print("请输入：");
        Scanner scanner = new Scanner(System.in);
        socketChannel.write(ByteBuffer.wrap(scanner.nextLine().getBytes()));
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (socketChannel.read(buffer) != -1) {
            if(buffer.position() > 0)
                break;
        }
        buffer.flip();
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        System.out.println("接收到的数据：\n" + new String(bytes));
        scanner.close();
        socketChannel.close();
    }
}
